var express = require('express');
var router = express.Router();
const svgCaptcha = require('svg-captcha');
var pool = require("../db/mysql");

/* GET home page. */
router.get('/', function (req, res, next) {
  res.setHeader("Content-Type", "text/html");
  res.render('index', { code: '' });
});

/* GET home page. */
router.get('/invite', function (req, res, next) {
  var code = req.query.inviteCode;
  res.setHeader("Content-Type", "text/html");
  res.render('index', { code: code });
});

router.get('/generalize', function (req, res) {
  var eth = req.query.eth;
  var querySql = "select INVITE_CODE from base_invite where ETH_ADDRESS ='" + eth + "'";
  var queryFun = (resolve, reject) => {
    pool.query(querySql, function (error, results, fields) {
      if (error) reject(error);
      if (results && results[0]) {
        resolve(results[0].INVITE_CODE);
      } else {
        reject(null);
      }
    });
  }
  new Promise(queryFun).then((data) => {
    res.setHeader("Content-Type", "text/html");
    res.render("generalize", { inviteCode: data });
  }).catch((error) => {
    res.setHeader("Content-Type", "text/html");
    res.render("index", { code: "" });
  });
});

router.get('/captcha', function (req, res) {
  const cap = svgCaptcha.create({ fontSize: 50, width: 100, height: 40 });
  res.setHeader('Content-Type', 'image/svg+xml');
  res.setHeader('Set-Cookie', 'text=' + cap.text);
  res.write(String(cap.data));
  res.end();
});
module.exports = router;
